import { useReq } from '@/components';
import request from '@/utils/request';
import React, { Children, cloneElement, isValidElement, useEffect } from 'react';

function OnsaleInfoProvider(props) {
  const { packageCode, children } = props;
  const xhr = useReq((code, options) =>
    request.post('/onsale/listProductsOnsaleInfo', { current: 0, pageSize: 1, t: { packageCode: code } }),
  );

  useEffect(() => {
    xhr.start(packageCode);
    return xhr.cancel;
  }, [packageCode]);

  const onSaleItem = xhr.result?.data?.records?.[0] || null;

  if (!onSaleItem) return null;

  return Children.map(children, (node) => (isValidElement(node) ? cloneElement(node, { onSaleItem }) : node));
}

export default OnsaleInfoProvider;
